package com.haircut.project.utils.category;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.haircut.project.vo.catetory.CateTreeVo;
import com.haircut.project.vo.catetory.CategoryTreeVo;
import com.haircut.project.vo.catetory.CategoryVo;
import com.haircut.sys.constant.Constants;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CategoryUtils {
    /**
     * 将数据转换成树行结果
     * @param list
     * @return
     */
    public static List<CategoryTreeVo> coverTree(List<CategoryVo> list){
        if(CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        Map<String,List<CategoryVo>> cateMap = list.stream().collect(Collectors.groupingBy(CategoryVo::getParentId));
        return coverSubTree(cateMap, Constants.DEFAULT_PARENT_ID);
    }

    /**
     * 处理下级分类的抓暖
     * @param cateMap
     * @param parentId
     * @return
     */
    private static List<CategoryTreeVo> coverSubTree(Map<String,List<CategoryVo>> cateMap,String parentId){
        List<CategoryVo> list = cateMap.get(parentId);
        if(ObjectUtil.isNull(list)){
            return null;
        }
        List<CategoryTreeVo> treeVoList = new ArrayList<>(list.size());
        CategoryTreeVo treeVo = null;
        for(CategoryVo categoryVo:list){
            treeVo = new CategoryTreeVo();
            BeanUtils.copyProperties(categoryVo,treeVo);
            treeVo.setChild(coverSubTree(cateMap,categoryVo.getId()));
            treeVoList.add(treeVo);
        }
        return treeVoList;
    }

    /**
     * 将数据转换成树行结果
     * @param list
     * @return
     */
    public static List<CateTreeVo> coverTreeVo(List<CategoryVo> list){
        if(CollUtil.isEmpty(list)){
            return Collections.emptyList();
        }
        Map<String,List<CategoryVo>> cateMap = list.stream().collect(Collectors.groupingBy(CategoryVo::getParentId));
        return coverSubTreeVo(cateMap, Constants.DEFAULT_PARENT_ID);
    }

    /**
     * 处理下级分类的抓暖
     * @param cateMap
     * @param parentId
     * @return
     */
    private static List<CateTreeVo> coverSubTreeVo(Map<String,List<CategoryVo>> cateMap,String parentId){
        List<CategoryVo> list = cateMap.get(parentId);
        if(ObjectUtil.isNull(list)){
            return null;
        }
        List<CateTreeVo> treeVoList = new ArrayList<>(list.size());
        CateTreeVo treeVo = null;
        for(CategoryVo categoryVo:list){
            treeVo = new CateTreeVo();
            treeVo.setValue(categoryVo.getId());
            treeVo.setText(categoryVo.getCategoryName());
            treeVo.setLabel(categoryVo.getCategoryName());
            treeVo.setChildren(coverSubTreeVo(cateMap,categoryVo.getId()));
            treeVoList.add(treeVo);
        }
        return treeVoList;
    }
}
